package com.lz.springboot.log4j2;

import java.util.Set;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;

@Component
@EnableApolloConfig({"log4j2"})
public class ApolloConfigLog4j2 {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigLog4j2.class);
	
	@ApolloConfig("log4j2")
	private Config config; 
	
	@Value("${rootLogger.level:info}")
	private String level;
	

	@ApolloConfigChangeListener("log4j2")
	private void anotherOnChange(ConfigChangeEvent changeEvent) {
		Set<String> configNames = config.getPropertyNames();
		for(String configName : configNames) {
			LOGGER.info("configName=[{}] configValue=[{}]", configName, config.getProperty(configName, ""));
		}
		
        if (changeEvent.isChanged("rootLogger.level")) {
            ConfigChange configChange = changeEvent.getChange("rootLogger.level");
            String newLevel = configChange.getNewValue();
            Level level = Level.toLevel(newLevel, Level.INFO);
            LoggerContext context = (LoggerContext) LogManager.getContext(false);
            Configuration conf = context.getConfiguration();

            //动态改变日志级别
            conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(level);
            context.updateLoggers(conf);
        }
	}


	@Override
	public String toString() {
		return "Log4j2Config [level=" + level + "]";
	}

}